<template>
  <el-button type="primary" @click="exportToExcel">导出Excel</el-button>
  <el-button type="danger" @click="deleteBatch()">删除所选项</el-button>
      <el-table
          height="80vh"
          max-height="90vh"
          ref="selectedRow"
          row-key="id"
          :data="AwardMessage"
          border style="width: 100%"
          :header-cell-style="{'text-align':'center'}"
          :cell-style="{'text-align':'center'}"
          v-model="selectedRow"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column :sortable="true" prop="awardName" label="奖项名称" width="500"/>
        <el-table-column :sortable="true" prop="awardData" label="获奖日期" width="180"/>
        <el-table-column :sortable="true" prop="awardLevel" label="奖项等级" width="120"/>
        <el-table-column :sortable="true" prop="competitionTypeName" label="竞赛类型" width="120" :filter-method="FilterHandler" :filter-multiple="false" :filters="competitionTypeNameHeaderSelect"/>
        <el-table-column :sortable="true" prop="teacher" label="指导老师" width="120"/>

        <el-table-column align="center" fixed="right" prop="operate" label="操作" width="300">
          <template v-slot="scope">
            <el-button
                size="small"
                type="primary" icon="Edit"
                @click="detailedInformation1(scope)"
            >查看详情
            </el-button>
            <el-button
                size="small"
                type="primary" icon="Edit"
                @click="openEditMessage(scope)"
            >修改
            </el-button>
            <el-button
                size="small"
                type="danger" icon="Edit"
                @click="deleteAwade(scope)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    <!--    查看详情弹窗-->
    <el-dialog
        v-model="detailedInformation"
        :close-on-click-modal="false"
        width="500px"
        height="700px"
        close-on-press-escape
        align-center
        draggable>
      <el-descriptions
          class="margin-top"
          title="查看详情"
          :column="1"
          border>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              奖项名称
            </div>
          </template>
          {{ this.detailMessage.awardName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              获奖日期
            </div>
          </template>
          {{ this.detailMessage.awardData }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              奖项等级
            </div>
          </template>
          {{ this.detailMessage.awardLevel }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              指导老师
            </div>
          </template>
          {{ this.detailMessage.teacher }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item" style="min-width: 100px">
              相关照片
            </div>
          </template>
          <img v-if="this.detailMessage.fileNo!==photoIp()+'null'"
               @click="previewImage(this.detailMessage.fileNo)" height="auto" width="100%"
               :src="this.detailMessage.fileNo">
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  <el-dialog
      v-model="seeEditMessage"
      :close-on-click-modal="false"
      width="500px"
      height="700px"
      close-on-press-escape
      align-center
      draggable>
    <el-form
        :model="user"
        ref="user"
        :rules="rule"
    >
      <el-form-item label="账号&nbsp;&nbsp;" prop="account" style="width: 80%">
        <el-input v-model="user.accountNo" placeholder="请输入" disabled
                  style="position: relative ;left: 13px ; width:756px "></el-input>
      </el-form-item>
      <el-form-item label="奖项名称" prop="awardName" style="width: 50%">
        <el-input v-model="user.awardName" placeholder="请输入奖项名称"></el-input>
      </el-form-item>
      <el-form-item label="指导老师" prop="teacher" style="width: 50%">
        <el-input v-model="user.teacher" placeholder="请输入指导老师"></el-input>
      </el-form-item>
      <el-form-item label="奖项等级" prop="awardLevel" style="width: 50%">
        <el-input v-model="user.awardLevel" placeholder="请写奖项等级(例：一等奖、二等奖)"></el-input>
      </el-form-item>
      <el-form-item prop="awardData" label="获奖日期">
        <el-date-picker
            v-model="user.awardData"
            type="date"
            placeholder="请选择日期"
            clearable
        />
      </el-form-item>
      <el-form-item label="奖项类型" prop="competitionTypeNo">
        <el-select
            v-model="user.competitionTypeNo"
            placeholder="请选择奖项类型"
            style="width: 50%"
        >
          <el-option
              v-for="x in allAwardGrade.grade"
              :key="x.competitionTypeNo"
              :label="x.competitionTypeName"
              :value="x.competitionTypeNo"
          />
        </el-select>
      </el-form-item>
      <el-upload
          accept=".jpeg,.png,.jpg"
          :headers="this.headerObject"
          id="uploadShowOrHide"
          class="upload-demo"
          drag
          :action="serverIp + '/api/info_award/uploadSign'"
          limit="1"
          :on-success="getFileNo"
      >
        <el-icon class="el-icon--upload">
          <upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件移在这 或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpeg/jpg/png 文件应小于 10MB
          </div>
        </template>
      </el-upload>
      <el-form-item>
        <el-button type="primary" @click="editMessage('user');">提交</el-button>
        <el-button @click="goBack('user')">取消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

    <div class="footer">
      <el-config-provider>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
            :pager-count="5"
            :page-sizes="[15, 30 , 60 ,  100 , 200 , 500 , 1000 , 2000 , 5000]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total">
        </el-pagination>
      </el-config-provider>
    </div>
  <el-image-viewer v-if="imgViewerVisible" :onClose="closeViewer" :url-list="this.urlList"/>
</template>

<script>
import request from "@/util/request.js";
import {photoIp, serverIp} from "../../../public/static/config.js";
import aes from "@/util/aes.js";
import {UploadFilled} from "@element-plus/icons-vue";
import {vDragable} from "element-plus-table-dragable";
import * as XLSX from 'xlsx'
export default {
  components: {UploadFilled},
  data() {
    return {
      imgViewerVisible: false,// 图片预览
      urlList: [],
      rule: {
        user:{},
        awardName: [
          { required: true, message: '请输入奖项名称', trigger: 'blur' },
        ],
        awardLevel:[
          { required: true, message: '请输入奖项等级', trigger: 'blur' },
        ],
        awardData: [
          { type: 'date', required: true, message: '请选择获奖日期', trigger: 'change' }
        ],
        competitionTypeNo: [
          { required: true, message: '请选择奖项类型', trigger: 'blur' }
        ],
      },
      headerObject:{
        "account" : JSON.parse(localStorage.getItem('user')).accountNo,
        "token" : JSON.parse(localStorage.getItem('user')).token
      },
      serverIp: serverIp,
      seeEditMessage :false,
      allAwardGrade :{
        grade :[],
      },
      detailedInformation: false,
      AwardMessage: [],
      detailMessage: {},
      NameOrStudentAccount: "",
      command: '全部',
      pageNum: 1, //页码
      pageSize: 15,  //页长
      total: 0,  //总表长
      instructorNameAll: [],
      instructorName: [],
      text :"" ,
      value: "",
      flag: false,  // 判断是否被筛选
      selectedRow: [], // 选中行
      competitionTypeNameHeaderSelect: [{
        text: '01-国际级',
        value: '01-国际级'
      },{
        text: '02-国家级',
        value: '02-国家级'
      },{
        text: '03-区域级',
        value: '03-区域级'
      },{
        text: '04-省级',
        value: '04-省级'
      },{
        text: '05-市级',
        value: '05-市级'
      },{
        text: '06-县级',
        value: '06-县级'
      },{
        text: '07-校级',
        value: '07-校级'
      },{
        text: '其他',
        value: '其他'
      }],
    };
  },
  //初始化加载
  created() {
    this.getAllAwardMessage(); //加载所有奖惩信息
    this.getAllAwardGrade();
  },
  methods: {
    photoIp() {
      return photoIp
    },
    // 选行
    handleSelectionChange(val) {
      this.selectedRow = val;
    },
    exportToExcel() {
      this.$nextTick(() => {
        // 获取 el-table 中的当前显示数据
        const tableData = this.selectedRow;
        // 确保数据存在
        if (tableData && tableData.length > 0) {
          // 将数据转换为 Excel 格式
          const worksheet = XLSX.utils.json_to_sheet(tableData);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

          // 下载 Excel 文件
          XLSX.writeFile(workbook, 'student_award.xlsx');
        } else {
          // 提示用户没有数据可供导出
          alert('没有数据可供导出！');
        }
      });
    },
    // 批量删除
    deleteBatch() {
      this.$confirm('此操作将永久删除该奖项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除，向服务器发送请求
        if (this.selectedRow.length === 0) {
          this.$message({
            type: "error",
            message: '未选择数据',
            center: true,
          })
          return
        }
        request.post("/info_award/deleteBatch", this.selectedRow).then(res => {
          this.$message({
            type: "success",
            message: '删除成功',
            center: true,
          })
          location.reload();
        })
      })
    },
    FilterHandler(value, row, column) {
      const property = column['property'];
      // 如果值是“其他”，则返回除了已有选项之外的字段
      if (value === '其他') {
        return !column['filters'].some(filter => filter.value === row[property]);
      }
      // 否则按照正常逻辑进行筛选
      return row[property] === value;
    },
    // 图片预览
    previewImage(src) {
      // 这里可以根据你的需求实现图片预览功能，比如弹出模态框等
      this.urlList.push(src)
      this.imgViewerVisible = true
    },
    // 关闭
    closeViewer() {
      if (this.imgViewerVisible) {
        this.imgViewerVisible = false
        this.urlList.pop();
      }
    },
    detailedInformation1(scope) {
      this.detailMessage = scope.row
      this.detailedInformation = true
    },

    //获取当前用户奖惩信息
    getAllAwardMessage() {
      request.get("/info_award/getOneByAccountNo?accountNo=" +JSON.parse(localStorage.getItem('user')).accountNo+"&pageNum="+this.pageNum+"&pageSize="+this.pageSize).then(res => {
        if (res.data.code === '200') {
          for (let key in res.data.data) {
            if (key === "records") {
              this.AwardMessage = res.data.data[key];
            } else if (key === "total") {
              this.total = res.data.data[key];
            }
          }
        }
      })
    },
    getAllAwardGrade(){
      request.get("/competition/all").then(res => {
        if (res.data.code === '200') {
          this.allAwardGrade.grade = res.data.data
        }
      })
    },
    editMessage(val){
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/info_award/edit", this.user).then(res => {
            if (res.data.code === '200') {
              this.$alert('提交成功', '提交成功', {
                confirmButtonText: '确定',
              }).then(() => {
                location.reload()
              });
            }
          })
        }
      })
    },
    getFileNo: function (res) {
      res = aes.decrypt(res)
      if (res.code != '200') {
        return;
      }
      this.user.fileNo = res.data
      this.$message.success('上传成功');
    },
    goBack(){
      this.seeEditMessage = false
      this.user = {}
    },
    openEditMessage(scope){
      this.seeEditMessage = true
      this.user = scope.row
    },
    //表尾分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAllAwardMessage();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getAllAwardMessage();
    },
    deleteAwade(scope) {
      this.$confirm('此操作将永久删除该奖项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除，向服务器发送请求
        request.get("/info_award/delete?accountNo=" + JSON.parse(localStorage.getItem('user')).accountNo + "&id=" + scope.row.id).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: "success",
              message: '删除成功',
              center: true,
            })
            location.reload();
          }
        })
      })
    }
  }
};

</script>


<style scoped>
table {
  border-collapse: collapse;
  text-align: center;
  vertical-align: middle;
  font-family: "宋体", SimSun;
}

th, td {
  border: 1px solid black;
  padding: 10px 0;
  font-family: "Times New Roman", Times, serif;
}

</style>
